<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;

use Auth;
use App\Models\Role;
use App\Http\ErrCode;

class AuthenticateController extends Controller
{
    public function authenticate(Request $request){
        // grab credentials from the request
        $credentials = $request->only('loginid', 'password');
        //未禁用的用户
        $credentials['status'] = 0;
        try {
            // attempt to verify the credentials and create a token for the user
            if (! $token = JWTAuth::attempt($credentials)) {
                return response()->json(json_error(ErrCode::AUTH_FAILED,'用户名或密码错误'), 401);
            }
        } catch (JWTException $e) {
            // something went wrong whilst attempting to encode the token
            return response()->json(json_error(ErrCode::SERVER_INTERNAL_ERROR,'创建token失败'), 500);
        }

        $user = Auth::user();
        $role = Role::find($user->role_id);
        $data = [
            'id'=>$user->id,
            'name'=>$user->name,
            'role'=>$role->name,
            'description'=>$user->description,
            'token'=>$token
        ];
        return response()->json(json_success($data));
    }

    public function refreshToken(){

    }
}
